using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WMS.RealTime.IServers.Interfaces;

namespace WMS.RealTime.Servers.Services
{
    /// <summary>
    /// 大屏数据后台服务
    /// </summary>
    public class DashboardBackgroundService : BackgroundService
    {
        private readonly IRealTimePushService _pushService;
        private readonly ILogger<DashboardBackgroundService> _logger;
        private readonly IConfiguration _configuration;

        public DashboardBackgroundService(
            IRealTimePushService pushService,
            ILogger<DashboardBackgroundService> logger,
            IConfiguration configuration)
        {
            _pushService = pushService;
            _logger = logger;
            _configuration = configuration;
        }
        /// <summary>
        /// 定时推送
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("大屏数据后台服务已启动");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    // 获取更新间隔配置，默认30秒
                    var updateInterval = _configuration.GetValue<int>("Dashboard:UpdateInterval", 30);
                    
                    _logger.LogInformation($"开始定时推送数据，间隔：{updateInterval}秒");

                    // 推送所有数据
                    await _pushService.PushAllDataAsync();

                    // 等待指定间隔
                    await Task.Delay(TimeSpan.FromSeconds(updateInterval), stoppingToken);
                }
                catch (OperationCanceledException)
                {
                    _logger.LogInformation("大屏数据后台服务已停止");
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "大屏数据后台服务执行出错");
                    
                    // 出错后等待10秒再重试
                    await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
                }
            }
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("正在停止大屏数据后台服务");
            await base.StopAsync(cancellationToken);
        }
    }
} 